﻿using LibNiconico.NiconicoApi.Mylist;
using NicoView.Model.Service.Results;
using NicoView.Model.Share.Service.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NicoView.Model.Service.Events
{
    public class NicoVideoConsoleEventArgs:NicoEventArgs
    {
        public NicoVideoConsoleEventArgs():this(null)
        {
           
        }

        private bool isEmpty
        {
            get
            {
                return console == null;
            }
        }

        private IEnumerable<NicoMylistItem> mylistItems;


        internal NicoVideoConsoleEventArgs(NicoVideoInfoConsoleEventArgs args)
        {
            console = args;

            if (args != null)
            {
                mylistItems = args.MylistItems;

                if (this.MylistItems != null && this.MylistItems.Count() > 0)
                {
                    this.AddTarget = this.MylistItems.First();
                }
            }
            else
            {
                mylistItems = new List<NicoMylistItem>();
            }

            

        }

        public string Id
        {
            get
            {
                if (isEmpty) return "";
                return console.Thumb.VideoId;
            }
        }

        public Uri ThumbnailUrl
        {
            get
            {
                if (isEmpty) return new Uri("http://live.nicovideo.jp/");
                return console.Thumb.ThumbnailUrl;
            }
        }

        public string Title
        {
            get
            {
                if (isEmpty) return "";
                return convertXmlEscape(console.Thumb.Title);
            }
        }

        public IEnumerable<NicoMylistItem> MylistItems
        {
            get
            {
                return mylistItems;
            }
        }



        public NicoMylistItem AddTarget
        {
            get;
            set;
        }


        public async Task<Result<bool>> AddExecuteAsync()
        {
            if (this.AddFunc != null)
            {
                return await this.AddFunc();
            }

            return new Result<bool>(false);
        }

        internal Func<Task<Result<bool>>> AddFunc;

        private static string convertXmlEscape(string text)
        {
            text = text.Replace("&amp;", "&");
            text = text.Replace("&lt;", "<");
            text = text.Replace("&gt;", ">");
            text = text.Replace("&quot;", "\"");
            text = text.Replace("&apos;", "'");
            return text;
        }

        private NicoVideoInfoConsoleEventArgs console { get; set; }
    }
}
